package com.huxiu.yd;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.NetworkHelper;
import com.huxiu.yd.net.model.ArticleItem;
import com.huxiu.yd.net.model.Comment;
import com.huxiu.yd.net.model.DiscoveryItem;
import com.huxiu.yd.net.responses.ArticlesResponse;
import com.huxiu.yd.net.responses.BaseResponse;
import com.huxiu.yd.net.responses.DiscoveryItemResponse;
import com.huxiu.yd.utils.Constants;
import com.huxiu.yd.utils.Global;
import com.huxiu.yd.utils.ImageUtils;
import com.huxiu.yd.utils.LogUtils;
import com.huxiu.yd.utils.Settings;
import com.huxiu.yd.utils.Utils;
import com.huxiu.yd.view.ArticleView;
import com.huxiu.yd.view.CommentViewHolder;
import com.huxiu.yd.view.EnrolledUserView;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;


public class DiscoveryDetailActivity extends BaseActivity implements OnClickListener {

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.right_image)
    ImageView rightImage;

    @InjectView(R.id.right_text)
    TextView rightText;

    @InjectView(R.id.web)
    WebView web;

    @InjectView(R.id.like_count)
    TextView likeCount;

    @InjectView(R.id.comment)
    TextView comment;

    @InjectView(R.id.content_container)
    LinearLayout contentContainer;

    @InjectView(R.id.title_image)
    ImageView titleImage;

    @InjectView(R.id.web_title)
    TextView webTitle;

    @InjectView(R.id.like_layout)
    View likeLayout;

    @InjectView(R.id.discovery_bottom)
    LinearLayout discoveryBottom;

    @InjectView(R.id.massive_test_like_count)
    TextView massiveTestLikeCount;

    @InjectView(R.id.massive_test_like_layout)
    FrameLayout massiveTestLikeLayout;

    @InjectView(R.id.massive_test_bottom)
    LinearLayout massiveTestBottom;

    @InjectView(R.id.register_button)
    Button registerButton;

    @InjectView(R.id.discovery_author)
    TextView discoveryAuthor;

    @InjectView(R.id.discovery_time)
    TextView discoveryTime;

    @InjectView(R.id.discovery_author_layout)
    LinearLayout discoveryAuthorLayout;

    @InjectView(R.id.bottom_container)
    LinearLayout bottomContainer;

    private DiscoveryItem item;

    private int type;

    private static final int TYPE_DISCOVERY = 0;

    private static final int TYPE_MASSIVE_TEST = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_discovery_detail);
        ButterKnife.inject(this);
        back.setOnClickListener(this);
        rightText.setVisibility(View.GONE);
        rightImage.setImageResource(R.drawable.ic_share);
        rightImage.setVisibility(View.VISIBLE);
        rightImage.setOnClickListener(this);
        discoveryAuthor.setOnClickListener(this);
        if (getIntent().hasExtra(Constants.DISCOVERY_ITEM_KEY)) {
            String data = getIntent().getStringExtra(Constants.DISCOVERY_ITEM_KEY);
            item = new Gson().fromJson(data, DiscoveryItem.class);
            type = TYPE_DISCOVERY;
        } else if (getIntent().hasExtra(Constants.MASSIVE_TEST_ITEM_KEY)) {
            String data = getIntent().getStringExtra(Constants.MASSIVE_TEST_ITEM_KEY);
            item = new Gson().fromJson(data, DiscoveryItem.class);
            type = TYPE_MASSIVE_TEST;
        }
        if (item.id == 0 && item.article_id != 0)
            item.id = item.article_id;
        updateWebViewSettings(web);

        reloadUIData();
        loadServerData();
    }

    void reloadUIData() {
        webTitle.setText(item.title);
        title.setText(type == TYPE_DISCOVERY ? R.string.discover : R.string.massive_test);
        discoveryBottom.setVisibility(type == TYPE_DISCOVERY ? View.VISIBLE : View.GONE);
        discoveryAuthorLayout.setVisibility(type == TYPE_DISCOVERY ? View.VISIBLE : View.GONE);
        discoveryAuthor.setText(item.name);
        discoveryTime.setText(Utils.getDateString(item.create_time));
        massiveTestBottom.setVisibility(type == TYPE_MASSIVE_TEST ? View.VISIBLE : View.GONE);
        massiveTestLikeCount.setText(Integer.toString(item.like_num));
        massiveTestLikeCount.setCompoundDrawablesWithIntrinsicBounds(
                item.liked() ? R.drawable.favorite_yes : R.drawable.favorite_no, 0, 0, 0);
        likeCount.setText(Integer.toString(item.like_num));
        likeCount.setCompoundDrawablesWithIntrinsicBounds(
                item.liked() ? R.drawable.like_selected : R.drawable.like_normal, 0, 0, 0);
        webviewSetContent(web, item.content);
        int width = Global.screenWidth - 2 * Utils.dip2px(10);
        int height = width * ((type == TYPE_DISCOVERY) ? 7 : 9) / 16;
        LayoutParams params = (LayoutParams) titleImage.getLayoutParams();
        params.width = width;
        params.height = height;
        titleImage.setLayoutParams(params);
        ImageLoader.getInstance()
                .displayImage(item.image + "!" + height + "x" + width, titleImage,
                        ImageUtils.getProductDisplayOption(item.getProductPlaceHolder()));
        comment.setText(type == TYPE_DISCOVERY ? R.string.say_something : R.string.attend_now);
        comment.setOnClickListener(this);
        likeLayout.setOnClickListener(this);
        massiveTestLikeLayout.setOnClickListener(this);
        registerButton.setBackgroundDrawable(getResources().getDrawable(item.getEnrollButtonBg()));
        registerButton.setText(item.getEnrollStatusPrompt2());
        registerButton.setTextColor(getResources().getColor(item.getEnrollStatusColor2()));
        registerButton.setOnClickListener(this);
    }

    void loadServerData() {
        String url = type == TYPE_DISCOVERY ? NetworkConstants.DISCOVERY_URL
                : NetworkConstants.TOPIC_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put(type == TYPE_DISCOVERY ? "article_id" : "id", Integer.toString(item.id));
        params.put("act", "contents");
        final int id = item.id;
        GsonRequest<DiscoveryItemResponse> request = new GsonRequest<>(url, Method.POST,
                DiscoveryItemResponse.class, true, params, new Listener<DiscoveryItemResponse>() {
            @Override
            public void onResponse(DiscoveryItemResponse response) {
                dismissProgress();
                if (response.isSuccess()) {
                    item = response.data;
                    item.id = id;
                    reloadUIData();
                    bottomContainer.removeAllViews();
                    if (response.comment != null || response.featured_comment != null) {
                        bindComments(response);
                    }
                    if (response.data.enroll_data != null && response.data.enroll_data.length > 0) {
                        LogUtils.d("enroll data size is " + response.data.enroll_data.length);
                        bindEnrolledUserView(response.data);
                    }
                    getRelatedArticles();
                } else {
                    Utils.showToast(response.msg);
                }
            }
        }, mErrorListener);
        mQueue.add(request);
//        mQueue.start();
    }

    private void bindEnrolledUserView(DiscoveryItem item) {
        View view = getLayoutInflater().inflate(R.layout.enrolled_user_grid_view,
                bottomContainer, false);
        int length = item.enroll_data.length;
        for (int i = 0; i < length && i < 9; i++) {
            int layoutId = getResources().getIdentifier("user" + (i + 1), "id",
                    "com.huxiu.yd");
            if (layoutId > 0) {
                EnrolledUserView enrolledUserView = (EnrolledUserView) view.findViewById(layoutId);
                enrolledUserView.setData(item.enroll_data[i].user_id, item.enroll_data[i].avatar,
                        item.enroll_data[i].name);
                enrolledUserView.setVisibility(View.VISIBLE);
            }
        }
        if (length >= 10) {
            EnrolledUserView enrolledUserView = (EnrolledUserView) view.findViewById(R.id.more);
            enrolledUserView.setMoreData(item.id);
            enrolledUserView.setVisibility(View.VISIBLE);
        }
        if (length < 5) {
            view.findViewById(R.id.line2).setVisibility(View.GONE);
        }
        bottomContainer.addView(view);
    }

    private void bindComments(DiscoveryItemResponse response) {
        int length = response.featured_comment.length;
        for (int i = 0; i < length; i++) {
            final Comment comment = response.featured_comment[i];
            View view = getLayoutInflater()
                    .inflate(R.layout.comment_list_item, bottomContainer, false);
            bindCommentView(length, i, comment, view, true);
            bottomContainer.addView(view);
        }
        length = response.comment.length;
        for (int i = 0; i < length && i < 5; i++) {
            Comment comment = response.comment[i];
            View view = getLayoutInflater()
                    .inflate(R.layout.comment_list_item, bottomContainer, false);
            bindCommentView(length, i, comment, view, false);
            bottomContainer.addView(view);
        }
        if (length > 5) {
            View viewMore = getLayoutInflater()
                    .inflate(R.layout.view_more_comments, bottomContainer, false);
            viewMore.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(DiscoveryDetailActivity.this,
                            ReviewListActivity.class);
                    intent.putExtra(Constants.ARTICLE_ID_KEY, Integer.toString(item.id));
                    startActivity(intent);
                }
            });
            bottomContainer.addView(viewMore);
            View divider = new View(this);
            divider.setLayoutParams(new LayoutParams(1, Utils.dip2px(8)));
            bottomContainer.addView(divider);
        }
        if (response.featured_comment.length == 0 && response.comment.length == 0) {
            View view = getLayoutInflater()
                    .inflate(R.layout.empty_comments_view, bottomContainer, false);
            View firstComment = view.findViewById(R.id.no_review);
            firstComment.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Settings.isLoggedIn()) {
                        Intent intent = new Intent(DiscoveryDetailActivity.this,
                                SubmitCommentActivity.class);
                        intent.putExtra(Constants.ARTICLE_ID_KEY, Integer.toString(item.id));
                        startActivityForResult(intent, 0);
                    } else {
                        Utils.askLogIn(DiscoveryDetailActivity.this);
                    }
                }
            });
            bottomContainer.addView(view);
        }
    }


    private void bindCommentView(int length, int i, final Comment comment, View view,
                                 boolean isFeatured) {
        final CommentViewHolder vh = new CommentViewHolder(view);
        vh.header.setVisibility(i == 0 ? View.VISIBLE : View.GONE);
        vh.bottomDivider.setVisibility(View.VISIBLE);
        vh.avatar.setUserInfo(comment.user_id, comment.avatar, comment.name);
        if (isFeatured) {
            vh.commentHeader.setText(getString(R.string.featured_comment) + "  (" + length + ")");
        } else {
            vh.commentHeader.setText(getString(R.string.comment) + "  (" + length + ")");
        }
        vh.name.setText(comment.name);
        vh.name.setCompoundDrawablesWithIntrinsicBounds(0, 0, comment
                .getUserDrawable(), 0);
        vh.name.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                vh.avatar.performClick();
            }
        });
        vh.time.setText(Utils.getDateString(comment.create_time));
        vh.content.setText(comment.content);
        vh.container.setOnClickListener(!isFeatured ? new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DiscoveryDetailActivity.this, CommentActivity.class);
                intent.putExtra("comment", comment);
                intent.putExtra("show_keyboard", false);
                intent.putExtra("is_discovery", type);
                startActivity(intent);
            }
        } : null);
        if (comment.recommend_num > 0 && !isFeatured) {
            vh.dianpingCount.setText(Integer.toString(comment.recommend_num));
            vh.dianpingCount.setVisibility(View.VISIBLE);
        } else {
            vh.dianpingCount.setVisibility(View.GONE);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.right_image:
                new AsyncTask<Void, Void, Void>() {
                    Bitmap bmp = null;

                    @Override
                    protected Void doInBackground(Void... params) {
                        bmp = ImageLoader.getInstance().loadImageSync(item.image);
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void aVoid) {
                        super.onPostExecute(aVoid);
                        Utils.launchShareActivity(DiscoveryDetailActivity.this,
                                "我正在独物参加" + item.title + "的免费众测！",
                                item.share_url,
                                type == TYPE_DISCOVERY ? "doc" : "topic", item.image,
                                item.description, bmp);
                    }
                }.execute();

                break;
            case R.id.comment:
                if (!Settings.isLoggedIn()) {
                    Utils.askLogIn(this);
                    return;
                }
                Intent intent = new Intent(this, SubmitCommentActivity.class);
                intent.putExtra(Constants.ARTICLE_ID_KEY, Integer.toString(item.id));
                startActivityForResult(intent, 0);
                break;
            case R.id.like_layout:
                if (!Settings.isLoggedIn()) {
                    Utils.askLogIn(this);
                    return;
                }
                like();
                break;
            case R.id.massive_test_like_layout:
                if (!Settings.isLoggedIn()) {
                    Utils.askLogIn(this);
                    return;
                }
                like();
                break;
            case R.id.register_button:
                if (item.user_status != DiscoveryItem.USER_STATUS_NOT_ATTENDED) {
                    return;
                }
                if (item.status == DiscoveryItem.ENROLL_STATUS_IN_PROGRESS && item.apply_status
                        != 3) {
                    if (Settings.isLoggedIn()) {
                        intent = new Intent(this, AttendActivity.class);
                        intent.putExtra(Constants.ARTICLE_ID_KEY, Integer.toString(item.id));
                        startActivity(intent);
                    } else {
                        Utils.askLogIn(this);
                    }
                }
                break;
            case R.id.discovery_author:
                intent = new Intent(DiscoveryDetailActivity.this, UserProfileActivity.class);
                intent.putExtra(Constants.USER_ID_KEY, item.user_id);
                intent.putExtra("avatar", item.avatar);
                intent.putExtra("username", item.name);
                startActivity(intent);
                break;
        }
    }

    private void like() {
        String url = type == TYPE_DISCOVERY ? NetworkConstants.DISCOVERY_URL : NetworkConstants
                .TOPIC_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("act", "user_operate");
        params.put(type == TYPE_DISCOVERY ? "article_id" : "id", String.valueOf(item.id));
        params.put("operate_type", type == TYPE_DISCOVERY ? "great_num" : "favorite");
        params.put("type", item.liked() ? "2" : "1");
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Method.POST, BaseResponse.class,
                true, params, new Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                if (response.isSuccess()) {
                    if (item.like_status == 1) {
                        item.like_num--;
                        item.like_status = 0;
                        if (type == TYPE_MASSIVE_TEST) {
                            Utils.showToast("取消成功");
                        }
                    } else {
                        item.like_num++;
                        item.like_status = 1;
                        if (type == TYPE_MASSIVE_TEST) {
                            Utils.showToast("关注成功");
                        }
                    }
                    likeCount.setText(Integer.toString(item.like_num));
                    likeCount.setCompoundDrawablesWithIntrinsicBounds(
                            item.liked() ? R.drawable.like_selected : R.drawable.like_normal, 0, 0,
                            0);
                    likeCount.setTextColor(getResources().getColor(item.liked() ? R.color
                            .gray5 : R.color.gray3));
                    massiveTestLikeCount.setText(Integer.toString(item.like_num));
                    massiveTestLikeCount.setCompoundDrawablesWithIntrinsicBounds(
                            item.liked() ? R.drawable.favorite_yes : R.drawable.favorite_no, 0, 0,
                            0);
                    massiveTestLikeCount.setTextColor(getResources().getColor(item.liked() ? R.color
                            .gray5 : R.color.gray3));

                }
            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Utils.showToast(R.string.generic_failure);
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
//        NetworkHelper.getInstance().getRequestQueue().start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case 0:
                refresh();
                break;
        }
    }

    private void getRelatedArticles() {
        if (type != TYPE_DISCOVERY) {
            return;
        }
        String url = NetworkConstants.DISCOVERY_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("article_id", Integer.toString(item.id));
        params.put("act", "get_relate_article");
        LogUtils.d("before getRelatedArticles!");
        GsonRequest<ArticlesResponse> request = new GsonRequest<>(url, Method.POST,
                ArticlesResponse.class, true, params, new Listener<ArticlesResponse>() {
            @Override
            public void onResponse(ArticlesResponse response) {
                if (response.isSuccess()) {
                    bindArticles(response.data);
                } else {
                    Utils.showToast(response.msg);
                }
            }
        }, null);
        mQueue.add(request);
//        mQueue.start();
    }

    private void bindArticles(ArticleItem[] data) {
        if (data == null || data.length == 0) {
            return;
        }
        View view = getLayoutInflater()
                .inflate(R.layout.related_article_title_view, bottomContainer, false);
        bottomContainer.addView(view);
        int articleViewWidth = (bottomContainer.getWidth() - 3 * Utils.dip2px(10)) / 2;
        int articleViewHeight = articleViewWidth * 7 / 16;
        for (int i = 0; i < data.length; i += 2) {
            View listItem = getLayoutInflater().inflate(R.layout.article_list_item,
                    bottomContainer, false);
            ArticleView left = (ArticleView) listItem.findViewById(R.id.left_article);
            left.setArticle(data[i], articleViewWidth, articleViewHeight);
            if (data.length > i + 1) {
                ArticleView right = (ArticleView) listItem.findViewById(R.id.right_article);
                right.setArticle(data[i + 1], articleViewWidth, articleViewHeight);
            } else {
                listItem.findViewById(R.id.right_article).setVisibility(View.INVISIBLE);
            }
            bottomContainer.addView(listItem);
        }
    }

    private void refresh() {
        loadServerData();
        showProgress();
    }
}
